package com.esiag.isidis.fi.pdsTeam.jms.consumer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import com.esiag.isidis.fi.pdsTeam.send.beans.ScalabilityMessage;

public class ScalabilityChargeConsumer implements MessageListener {

  private Integer mTotalCharge = 0;
  private Integer mMaxCharge = 2;
  private List<Message> mSynchroMessages = Collections.synchronizedList(new ArrayList<Message>());

  public ScalabilityChargeConsumer() {

  }
  
  public void addObject(Message pObject){
	  mSynchroMessages.add(pObject);
  }
  
  public Message retrieveObject(){
	  if(mSynchroMessages.size() > 0){
		  return mSynchroMessages.remove(0);
	  }
	  return null;
  }

  public void notifyAdmin() {

  }
//recoie la charge enoyée par (sendCharge-> producer.send()) et l'ajoute à sa charge
  public void onMessage(Message pMessage) {
    synchronized (mMaxCharge) {
      try {
        ScalabilityMessage sm = (ScalabilityMessage) ((ObjectMessage) pMessage).getObject();
        mTotalCharge += sm.getCharge();
        if (mTotalCharge == mMaxCharge) {
          notifyAdmin();
        }
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }
  }

  public Integer getTotalCharge() {
    return mTotalCharge;
  }

  public void setTotalCharge(Integer pTotalCharge) {
    mTotalCharge = pTotalCharge;
  }

  public Integer getMaxCharge() {
    return mMaxCharge;
  }

  public void setMaxCharge(Integer pMaxCharge) {
    synchronized (mMaxCharge) {
      mMaxCharge = pMaxCharge;
    }
  }

  public boolean isOverLoaded() {
    boolean res = false;
    synchronized (mMaxCharge) {
      res = mTotalCharge >= mMaxCharge;
    }
    return res;
  }
}
